package tvseries.utils;

import java.net.MalformedURLException;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;

import org.apache.log4j.Logger;

import tvseries.entity.Episode;
import tvseries.entity.Series;

public class SMBFileUtils
{
	private static final Logger log = Logger.getLogger(SMBFileUtils.class);

	private static SMBFileUtils smbfu = null;

	public static void main(String[] args)
	{
		log.info("Welcome - SMBFIleUtils Test");
		smbfu = new SMBFileUtils();
		smbfu.run();
	}

	private void run()
	{
		Series series = (Series) HibernateUtil.load(Series.class, "0162065");
		log.info("Series title: " + series.getTitle());
		Set<String> files = smbfu.getSeriesFiles(series);
		processSeries(series, files);
	}

	private void processSeries(Series series, Set<String> files)
	{
		log.debug("processing series: " + series.getTitle());
		
		Set<Episode> episodes = series.getEpisodes();
		for (Episode e : episodes)
		{
			String season = e.getSeason() < 10 ? "0" + e.getSeason() : e.getSeason() + "";
			String episode = e.getEpisode() < 10 ? "0" + e.getEpisode() : "" + e.getEpisode();
			String file = season + "x" + episode;
			if (files.contains(file) && !"Available".equals(e.getStatus()))
			{
				e.setStatus("Available");
				HibernateUtil.persist(e);
			}
		}
	}

	private Set<String> getSeriesFiles(Series series)
	{
		String regex = "(\\d\\dx\\d\\d)";
		Pattern p = Pattern.compile(regex);
		
		String base = PropUtil.get("smb.filesystem.base");
		String seriesBase = base + "/" + series.getTitle() + "/";

		Set<String> files = new HashSet<String>();
		try
		{
			SmbFile sfb = new SmbFile(seriesBase);
			SmbFile[] seasons = sfb.listFiles();
			if (seasons == null || seasons.length == 0)
			{
				log.warn("no seasons found for: " + series.getTitle());
				return files;
			}

			for (SmbFile s : seasons)
			{
				if (s.isFile() || !s.getName().toLowerCase().startsWith("season"))
				{
					log.info("is not a valid season folder: " + s.getName());
					continue;
				}

				SmbFile[] episodes = s.listFiles();
				if (episodes == null || episodes.length == 0)
				{
					log.warn("no episodes found for: " + series.getTitle() + "/" + s.getName());
					continue;
				}

				for (SmbFile e : episodes)
				{
					if (!isVideo(e.getName()))
						continue;

					Matcher m = p.matcher(e.getName());
					while (m.find())
					{
						if (log.isDebugEnabled())
							log.debug(m.group(1));

						files.add(m.group(1));
					}
				}
			}
		}
		catch (MalformedURLException mue)
		{
			log.error("error reading folder: " + seriesBase, mue);
			return null;
		}
		catch (SmbException se)
		{
			log.error("error opening folder: " + seriesBase, se);
			return null;
		}

		return files;
	}

	private static boolean isVideo(String name)
	{
		if (name.endsWith("avi"))
			return true;

		if (name.endsWith("mpg"))
			return true;

		if (name.endsWith("mp4"))
			return true;

		if (name.endsWith("mkv"))
			return true;

		if (name.endsWith("ogg"))
			return true;

		if (name.endsWith("wmv"))
			return true;

		return false;
	}
}
